package com.yihengyi.demo.test;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class CustomTrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
        // 客户端证书验证逻辑（在这个场景下通常不需要实现）
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
        System.out.println("checkServerTrusted:" + s);
        // 服务器证书验证逻辑
        // 注意：这里我们没有实现任何验证逻辑，这意味着它会信任所有的服务器证书
        // 在生产环境中，你需要实现适当的验证逻辑
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    public static SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
        // 创建一个空的TrustManager数组并使用我们的CustomTrustManager
        TrustManager[] trustManagers = new TrustManager[]{new CustomTrustManager()};

        // 初始化一个SSLContext来使用这些TrustManagers
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());

        return sslContext;
    }
}
